package com.example.project.frag_chart;


import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.android.volley.VolleyError;
import com.example.project.MyApplication;
import com.example.project.R;
import com.example.project.adapter.ChartItemAdapter;
import com.example.project.bean.ChartItemBean;
import com.example.project.db.DBManager;
import com.example.project.volley.ConstantUtil;
import com.example.project.volley.Params;
import com.example.project.volley.VolleyInterface;
import com.example.project.volley.VolleyRequest;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
abstract public class BaseChartFragment extends Fragment {
    ListView chartLv;
    int year;
    int month;
    List<ChartItemBean> mDatas;   //数据源
    private ChartItemAdapter itemAdapter;
    BarChart barChart;     //代表柱状图的控件
    TextView chartTv;     //如果没有收支情况，显示的TextView
    int mainId;
    PieChart mPieChart; //图表控件

    //创建该fragment对应的视图
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainId= MyApplication.getMainId();
        View view =  inflater.inflate( R.layout.fragment_incom_chart, container, false);
        chartLv = view.findViewById( R.id.frag_chart_lv);
        //1.初始化组件
        mPieChart = view.findViewById(R.id.mPieChart);
        set();
        //获取Activity传递的数据
        Bundle bundle = getArguments();
        year = bundle.getInt("year");
        month = bundle.getInt("month");
        //设置数据源
        mDatas = new ArrayList<>();
        //设置适配器
        itemAdapter = new ChartItemAdapter(getContext(), mDatas);
        chartLv.setAdapter(itemAdapter);
        loadData(year,month,0);
        return view;
    }


    private void set(){
        /*折线饼状图*/
        System.out.println("折线图");
        mPieChart.setUsePercentValues(true); //设置是否使用百分值,默认不显示
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setDragDecelerationFrictionCoef(0.95f);

        //是否设置中心文字
        mPieChart.setDrawCenterText(true);
        //绘制中间文字
        SpannableString sp = new SpannableString("个人剖析图");
        mPieChart.setCenterText(sp);
        mPieChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        //设置是否为实心图，以及空心时 中间的颜色
        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        //设置圆环信息
        mPieChart.setTransparentCircleColor(Color.WHITE);//设置透明环颜色
        mPieChart.setTransparentCircleAlpha(110);//设置透明环的透明度
        mPieChart.setHoleRadius(55f);//设置内圆的大小
        mPieChart.setTransparentCircleRadius(60f);//设置透明环的大小

        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        //选中变大
        mPieChart.setHighlightPerTapEnabled(true);

        //模拟数据
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        entries.add(new PieEntry(80, "颜值"));
        entries.add(new PieEntry(100, "智慧"));
        entries.add(new PieEntry(50, "身材"));
        entries.add(new PieEntry(50, "性格"));
        entries.add(new PieEntry(20, "声音"));

        //设置数据
        setData(entries);

        //默认动画
        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        //设置图例
        Legend l = mPieChart.getLegend();
        //设置显示的位置，低版本用的是setPosition();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        //设置是否显示图例
        l.setDrawInside(false);
        l.setEnabled(true);

        // 输入图例标签样式
        mPieChart.setEntryLabelColor(Color.BLUE);
        mPieChart.setEntryLabelTextSize(18f);

    }


    //设置数据
    private void setData(ArrayList<PieEntry> entries) {
        PieDataSet dataSet = new PieDataSet(entries, "");
        //设置个饼状图之间的距离
        dataSet.setSliceSpace(0f);
        //颜色的集合，按照存放的顺序显示
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);

        //设置折线
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        //设置线的长度
        dataSet.setValueLinePart1Length(0.3f);
        dataSet.setValueLinePart2Length(0.3f);
        //设置文字和数据图外显示
        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        //百分比设置
        data.setValueFormatter(new PercentFormatter());
        //文字的颜色
        data.setValueTextSize(14f);
        data.setValueTextColor(Color.BLACK);
        mPieChart.setData(data);
        // 撤销所有的亮点
        mPieChart.highlightValues(null);
        mPieChart.invalidate();
    }

    public void loadData(int year,int month,int kind) {
        List<ChartItemBean> list = DBManager.getChartListFromAccounttb(year, month, kind,mainId);
        System.out.println( "list:"+list );
        mDatas.clear();
        mDatas.addAll(list);
        itemAdapter.notifyDataSetChanged();
    }

    //查询指定年份和月份的收入或者支出每一种类型的总钱数
    private void volleyMonthNum(String year,String month,String kind,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.MONTHNUM, "MonthNum", Params.MonthNums(year,month,kind,mainId),new VolleyInterface( getContext() ){
            @Override
            public void onMySuccess(String jsonStr) {
                JSONArray jsonArray = null;
                // 初始化list数组对象
                ArrayList<ChartItemBean> list = new ArrayList<>();
                try {
                    jsonArray = new JSONArray(jsonStr);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject juser = jsonArray.getJSONObject( i );
                        ChartItemBean chartItemBean = new ChartItemBean();
                        chartItemBean.setsImageId( Integer.parseInt( juser.getString( "sImageId" ) ) );
                        chartItemBean.setRatio( Float.parseFloat( juser.getString( "ratio" ) ) );
                        chartItemBean.setTotalMoney( Float.parseFloat( juser.getString( "total" ) ) );
                        chartItemBean.setType( juser.getString( "typename" ) );
                        list.add( chartItemBean );
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                System.out.println( "list:"+list.size() );
                mDatas.clear();
                mDatas.addAll(list);
                itemAdapter.notifyDataSetChanged();
            }
            @Override
            public void onMyError(VolleyError error) {

            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {
            }
        });

    }

}
